<template>
  <div class="test-mode">
    <div class="header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">← 返回首页</button>
        <h1>测试模式</h1>
      </div>
      <div class="gamepad-status">
        <div class="gamepad-indicator" :class="{ connected: gamepadConnected }">
          <span class="gamepad-icon">🎮</span>
          <span class="gamepad-text">{{ gamepadStatus }}</span>
        </div>
      </div>
    </div>
    
    <div class="test-container">
      <div class="control-panel">
        <h2>车辆控制面板</h2>
        <div class="controls">
          <div class="direction-controls">
            <button class="control-btn" @click="move('forward')">↑ 前进</button>
            <div class="horizontal-controls">
              <button class="control-btn" @click="move('left')">← 左转</button>
              <button class="control-btn stop" @click="stop()">停止</button>
              <button class="control-btn" @click="move('right')">右转 →</button>
            </div>
            <button class="control-btn" @click="move('backward')">↓ 后退</button>
          </div>
        </div>
      </div>
      
      <div class="status-panel">
        <h2>状态信息</h2>
        <div class="status-info">
          <div class="status-item">
            <span class="label">当前状态:</span>
            <span class="value">{{ currentStatus }}</span>
          </div>
          <div class="status-item">
            <span class="label">速度:</span>
            <span class="value">{{ speed }} m/s</span>
          </div>
          <div class="status-item">
            <span class="label">方向:</span>
            <span class="value">{{ direction }}</span>
          </div>
        </div>
      </div>
      
      <div class="gamepad-panel" v-if="gamepadConnected">
        <h2>手柄映射检测</h2>
        <div class="gamepad-mapping">
          <div class="buttons-section">
            <h3>按键状态</h3>
            <div class="buttons-grid">
              <div v-for="(button, index) in gamepadButtons" :key="index" 
                   class="button-item" :class="{ pressed: button.pressed }">
                <span class="button-label">{{ getButtonName(index) }}</span>
                <span class="button-value">{{ button.value.toFixed(2) }}</span>
              </div>
            </div>
          </div>
          <div class="axes-section">
            <h3>摇杆/扳机</h3>
            <div class="axes-grid">
              <div v-for="(axis, index) in gamepadAxes" :key="index" class="axis-item">
                <span class="axis-label">{{ getAxisName(index) }}</span>
                <div class="axis-bar">
                  <div class="axis-fill" :style="{ width: Math.abs(axis) * 100 + '%', backgroundColor: axis >= 0 ? '#74b9ff' : '#e17055' }"></div>
                </div>
                <span class="axis-value">{{ axis.toFixed(2) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="log-panel">
        <h2>操作日志</h2>
        <div class="log-content">
          <div v-for="(log, index) in logs" :key="index" class="log-item">
            <span class="timestamp">{{ log.time }}</span>
            <span class="action">{{ log.action }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TestMode',
  data() {
    return {
      currentStatus: '待机',
      speed: 0,
      direction: '无',
      logs: [],
      gamepadConnected: false,
      gamepadStatus: '未连接手柄',
      gamepadCheckInterval: null,
      gamepadButtons: [],
      gamepadAxes: [],
      gamepadUpdateInterval: null
    }
  },
  mounted() {
    this.initGamepadDetection()
  },
  beforeUnmount() {
    if (this.gamepadCheckInterval) {
      clearInterval(this.gamepadCheckInterval)
    }
    if (this.gamepadUpdateInterval) {
      clearInterval(this.gamepadUpdateInterval)
    }
    window.removeEventListener('gamepadconnected', this.onGamepadConnected)
    window.removeEventListener('gamepaddisconnected', this.onGamepadDisconnected)
  },
  methods: {
    goBack() {
      this.$router.push('/')
    },
    move(direction) {
      this.currentStatus = '移动中'
      this.speed = 1.5
      this.direction = this.getDirectionText(direction)
      this.addLog(`车辆${this.direction}`)
    },
    stop() {
      this.currentStatus = '停止'
      this.speed = 0
      this.direction = '无'
      this.addLog('车辆停止')
    },
    getDirectionText(dir) {
      const directions = {
        forward: '前进',
        backward: '后退',
        left: '左转',
        right: '右转'
      }
      return directions[dir] || '未知'
    },
    addLog(action) {
      const now = new Date()
      const time = now.toLocaleTimeString()
      this.logs.unshift({ time, action })
      if (this.logs.length > 10) {
        this.logs.pop()
      }
    },
    initGamepadDetection() {
      // 检查浏览器是否支持Gamepad API
      if (!navigator.getGamepads) {
        this.gamepadStatus = '浏览器不支持手柄'
        return
      }

      // 监听手柄连接事件
      window.addEventListener('gamepadconnected', this.onGamepadConnected)
      window.addEventListener('gamepaddisconnected', this.onGamepadDisconnected)

      // 定期检查手柄状态
      this.gamepadCheckInterval = setInterval(this.checkGamepadStatus, 1000)
      
      // 初始检查
      this.checkGamepadStatus()
    },
    onGamepadConnected(event) {
      this.gamepadConnected = true
      this.gamepadStatus = `已连接: ${event.gamepad.id}`
      this.addLog(`手柄已连接: ${event.gamepad.id}`)
      this.startGamepadUpdate()
    },
    onGamepadDisconnected(event) {
      this.gamepadConnected = false
      this.gamepadStatus = '手柄已断开'
      this.addLog(`手柄已断开: ${event.gamepad.id}`)
      this.stopGamepadUpdate()
      
      // 延迟重置状态
      setTimeout(() => {
        if (!this.gamepadConnected) {
          this.gamepadStatus = '未连接手柄'
        }
      }, 2000)
    },
    checkGamepadStatus() {
      const gamepads = navigator.getGamepads()
      let hasConnectedGamepad = false
      
      for (let i = 0; i < gamepads.length; i++) {
        if (gamepads[i] && gamepads[i].connected) {
          hasConnectedGamepad = true
          if (!this.gamepadConnected) {
            this.gamepadConnected = true
            this.gamepadStatus = `已连接: ${gamepads[i].id}`
            this.addLog(`检测到手柄: ${gamepads[i].id}`)
            this.startGamepadUpdate()
          }
          break
        }
      }
      
      if (!hasConnectedGamepad && this.gamepadConnected) {
        this.gamepadConnected = false
        this.gamepadStatus = '未连接手柄'
        this.addLog('手柄连接丢失')
        this.stopGamepadUpdate()
      }
    },
    startGamepadUpdate() {
      if (this.gamepadUpdateInterval) {
        clearInterval(this.gamepadUpdateInterval)
      }
      this.gamepadUpdateInterval = setInterval(this.updateGamepadState, 50) // 20fps
    },
    stopGamepadUpdate() {
      if (this.gamepadUpdateInterval) {
        clearInterval(this.gamepadUpdateInterval)
        this.gamepadUpdateInterval = null
      }
      this.gamepadButtons = []
      this.gamepadAxes = []
    },
    updateGamepadState() {
      const gamepads = navigator.getGamepads()
      for (let i = 0; i < gamepads.length; i++) {
        if (gamepads[i] && gamepads[i].connected) {
          this.gamepadButtons = Array.from(gamepads[i].buttons)
          this.gamepadAxes = Array.from(gamepads[i].axes)
          break
        }
      }
    },
    getButtonName(index) {
      const buttonNames = {
        0: 'A/X',
        1: 'B/○',
        2: 'X/□',
        3: 'Y/△',
        4: 'LB/L1',
        5: 'RB/R1',
        6: 'LT/L2',
        7: 'RT/R2',
        8: 'Back/Select',
        9: 'Start/Options',
        10: 'LS/L3',
        11: 'RS/R3',
        12: '↑',
        13: '↓',
        14: '←',
        15: '→',
        16: 'Home/PS'
      }
      return buttonNames[index] || `按键${index}`
    },
    getAxisName(index) {
      const axisNames = {
        0: '左摇杆 X',
        1: '左摇杆 Y',
        2: '右摇杆 X',
        3: '右摇杆 Y'
      }
      return axisNames[index] || `轴${index}`
    }
  }
}
</script>

<style scoped>
.test-mode {
  width: 100%;
  height: 100vh;
  min-height: 100vh;
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  padding: 20px;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;
}



.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2rem;
  gap: 1rem;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.gamepad-status {
  display: flex;
  align-items: center;
}

.gamepad-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.9);
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
  border: 2px solid #ddd;
}

.gamepad-indicator.connected {
  background: rgba(116, 185, 255, 0.9);
  border-color: #74b9ff;
  color: white;
}

.gamepad-icon {
  font-size: 1.2rem;
  filter: grayscale(100%);
  transition: filter 0.3s ease;
}

.gamepad-indicator.connected .gamepad-icon {
  filter: grayscale(0%);
}

.gamepad-text {
  font-size: 0.9rem;
  font-weight: bold;
  color: #666;
}

.gamepad-indicator.connected .gamepad-text {
  color: white;
}

.back-btn {
  background: white;
  border: none;
  padding: 10px 20px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: #f1f2f6;
  transform: translateY(-2px);
}

.header h1 {
  color: white;
  font-size: 2.5rem;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.test-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto;
  gap: 2rem;
  max-width: 1400px;
  margin: 0 auto;
}

.gamepad-panel {
  grid-column: 1 / -1;
}

.control-panel, .status-panel, .log-panel, .gamepad-panel {
  background: white;
  border-radius: 15px;
  padding: 1.5rem;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.control-panel h2, .status-panel h2, .log-panel h2, .gamepad-panel h2 {
  color: #333;
  margin-bottom: 1rem;
  text-align: center;
}

.gamepad-mapping {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
}

.buttons-section h3, .axes-section h3 {
  color: #666;
  margin-bottom: 1rem;
  font-size: 1.2rem;
}

.buttons-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 8px;
}

.button-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px solid transparent;
  transition: all 0.2s ease;
}

.button-item.pressed {
  background: #74b9ff;
  color: white;
  border-color: #0984e3;
  transform: scale(1.05);
}

.button-label {
  font-size: 0.8rem;
  font-weight: bold;
  margin-bottom: 4px;
}

.button-value {
  font-size: 0.7rem;
  opacity: 0.8;
}

.axes-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.axis-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.axis-label {
  font-size: 0.9rem;
  font-weight: bold;
  min-width: 80px;
  color: #666;
}

.axis-bar {
  flex: 1;
  height: 20px;
  background: #e9ecef;
  border-radius: 10px;
  position: relative;
  overflow: hidden;
}

.axis-fill {
  height: 100%;
  border-radius: 10px;
  transition: all 0.1s ease;
}

.axis-value {
  font-size: 0.8rem;
  font-weight: bold;
  min-width: 40px;
  text-align: right;
  color: #666;
}

.direction-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.horizontal-controls {
  display: flex;
  gap: 10px;
}

.control-btn {
  background: #74b9ff;
  color: white;
  border: none;
  padding: 15px 20px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: bold;
  transition: all 0.3s ease;
  min-width: 80px;
}

.control-btn:hover {
  background: #0984e3;
  transform: translateY(-2px);
}

.control-btn.stop {
  background: #e17055;
}

.control-btn.stop:hover {
  background: #d63031;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.status-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.label {
  font-weight: bold;
  color: #333;
}

.value {
  color: #74b9ff;
  font-weight: bold;
}

.log-content {
  max-height: 300px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.log-item {
  display: flex;
  justify-content: space-between;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 0.9rem;
}

.timestamp {
  color: #666;
  font-size: 0.8rem;
}

.action {
  color: #333;
  font-weight: bold;
}

@media (max-width: 1024px) {
  .test-container {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .gamepad-mapping {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .buttons-grid {
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  }
}

@media (max-width: 768px) {
  .header h1 {
    font-size: 1.8rem;
  }
  
  .control-btn {
    padding: 12px 16px;
    font-size: 0.9rem;
  }
}
</style>